package com.markerhub.config;

import com.markerhub.security.JwtAuthenticationEntryPoint;
import com.markerhub.security.JwtAccessDeniedHandler;
import com.markerhub.security.JwtAuthenticationFilter;
import com.markerhub.security.UserDetailServiceImpl;
import com.markerhub.service.SysUserService;
import com.markerhub.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Autowired
    JwtAccessDeniedHandler jwtAccessDeniedHandler;

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserDetailServiceImpl userDetailService;

    @Autowired
    SysUserService sysUserService;

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
        return new JwtAuthenticationFilter(
            authenticationManagerBean(),
            jwtUtils,
            userDetailService,
            sysUserService
        );
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new PasswordEncoder() {
            @Override
            public String encode(CharSequence rawPassword) {
                return rawPassword != null ? rawPassword.toString() : "";
            }

            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                return true; // 总是返回true
            }
        };
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
            // 禁用默认的登录表单，使用我们自定义的Controller
            .formLogin().disable()
            // 禁用默认的登出处理，使用我们自定义的Controller
            .logout().disable()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            // 允许访问登录接口和Swagger相关接口
            // 将导航菜单和用户信息接口放回白名单，因为它们自身有token验证
            .antMatchers("/api/auth/login", "/api/auth/logout", 
                         "/api/auth/sys/userInfo", // 用户信息接口放回白名单
                         "/api/sys-menu/nav", // 导航菜单接口放回白名单
                         "/swagger-ui.html", "/swagger-ui/", 
                         "/swagger-resources/**", "/v2/api-docs", 
                         "/v3/api-docs/**", "/webjars/**").permitAll()
            // 其他请求需要认证
            .anyRequest().authenticated()
            .and()
            .exceptionHandling()
            .authenticationEntryPoint(jwtAuthenticationEntryPoint)
            .accessDeniedHandler(jwtAccessDeniedHandler)
            .and()
            // 将JWT过滤器放在UsernamePasswordAuthenticationFilter之前，确保token验证优先执行
            .addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

        http.headers().frameOptions().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder());
    }
}
